// 第三方登录工具

// 平台信息接口
export interface PlatformInfo {
  platform: 'h5' | 'wechat' | 'alipay' | 'douyin'
  version: string
  system: string
  brand?: string
  model?: string
}

/**
 * 获取平台信息
 */
export const getPlatformInfo = (): PlatformInfo => {
  let platform: PlatformInfo['platform'] = 'h5'

  // 检测当前环境
  if (typeof window !== 'undefined') {
    const userAgent = navigator.userAgent.toLowerCase()
    if (userAgent.includes('micromessenger')) {
      platform = 'wechat'
    } else if (userAgent.includes('alipayclient')) {
      platform = 'alipay'
    } else if (userAgent.includes('toutiao')) {
      platform = 'douyin'
    }
  }

  const systemInfo = typeof window !== 'undefined' && window.uni ? uni.getSystemInfoSync() : {
    version: '1.0.0',
    system: navigator?.platform || 'Unknown',
    brand: 'H5',
    model: 'Browser'
  }

  return {
    platform,
    version: systemInfo.version,
    system: systemInfo.system,
    brand: systemInfo.brand,
    model: systemInfo.model
  }
}

/**
 * 微信登录
 */
export const wechatLogin = (): Promise<{
  code: string
  userInfo?: any
}> => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    // 微信小程序登录
    uni.login({
      provider: 'weixin',
      success: (loginRes) => {
        if (loginRes.code) {
          // 获取用户信息
          uni.getUserProfile({
            desc: '用于完善用户资料',
            success: (profileRes) => {
              resolve({
                code: loginRes.code,
                userInfo: profileRes.userInfo
              })
            },
            fail: () => {
              // 即使获取用户信息失败，也返回code
              resolve({
                code: loginRes.code
              })
            }
          })
        } else {
          reject(new Error(loginRes.errMsg || '微信登录失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '微信登录失败'))
      }
    })
    // #endif

    // #ifdef H5
    // H5微信登录（需要配置公众号）
    if (isWeixinBrowser()) {
      // 微信浏览器内的登录
      const appId = 'YOUR_WECHAT_APPID'
      const redirectUri = encodeURIComponent(window.location.href)
      const state = Date.now().toString()

      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`

      window.location.href = url
    } else {
      reject(new Error('请在微信浏览器中打开'))
    }
    // #endif

    // #ifndef MP-WEIXIN
    // #ifndef H5
    reject(new Error('当前平台不支持微信登录'))
    // #endif
    // #endif
  })
}

/**
 * 支付宝登录
 */
export const alipayLogin = (): Promise<{
  authCode: string
  userInfo?: any
}> => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-ALIPAY
    // 支付宝小程序登录
    my.getAuthCode({
      scopes: ['auth_user'],
      success: (res) => {
        if (res.authCode) {
          // 获取用户信息
          my.getOpenUserInfo({
            success: (userRes) => {
              resolve({
                authCode: res.authCode,
                userInfo: userRes.response ? JSON.parse(userRes.response) : undefined
              })
            },
            fail: () => {
              resolve({
                authCode: res.authCode
              })
            }
          })
        } else {
          reject(new Error('支付宝登录失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errorMessage || '支付宝登录失败'))
      }
    })
    // #endif

    // #ifndef MP-ALIPAY
    reject(new Error('当前平台不支持支付宝登录'))
    // #endif
  })
}

/**
 * 抖音登录
 */
export const douyinLogin = (): Promise<{
  code: string
  userInfo?: any
}> => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-TOUTIAO
    // 抖音小程序登录
    tt.login({
      success: (res) => {
        if (res.code) {
          // 获取用户信息
          tt.getUserInfo({
            success: (userRes) => {
              resolve({
                code: res.code,
                userInfo: userRes.userInfo
              })
            },
            fail: () => {
              resolve({
                code: res.code
              })
            }
          })
        } else {
          reject(new Error('抖音登录失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '抖音登录失败'))
      }
    })
    // #endif

    // #ifndef MP-TOUTIAO
    reject(new Error('当前平台不支持抖音登录'))
    // #endif
  })
}

/**
 * 判断是否在微信浏览器中
 */
export const isWeixinBrowser = (): boolean => {
  // #ifdef H5
  const ua = navigator.userAgent.toLowerCase()
  return ua.indexOf('micromessenger') !== -1
  // #endif

  return false
}

/**
 * 判断是否在支付宝浏览器中
 */
export const isAlipayBrowser = (): boolean => {
  // #ifdef H5
  const ua = navigator.userAgent.toLowerCase()
  return ua.indexOf('alipayclient') !== -1
  // #endif

  return false
}

/**
 * 获取URL参数（H5用）
 */
export const getUrlParam = (name: string): string | null => {
  // #ifdef H5
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get(name)
  // #endif

  return null
}

/**
 * 生物识别认证
 */
export const biometricAuth = (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    // 微信小程序生物识别
    uni.checkIsSupportSoterAuthentication({
      success: (res) => {
        if (res.supportMode.includes('fingerPrint') || res.supportMode.includes('facial')) {
          uni.startSoterAuthentication({
            requestAuthModes: ['fingerPrint', 'facial'],
            challenge: Date.now().toString(),
            authContent: '请验证指纹或面容',
            success: () => {
              resolve(true)
            },
            fail: (err) => {
              reject(new Error(err.errMsg || '生物识别失败'))
            }
          })
        } else {
          reject(new Error('设备不支持生物识别'))
        }
      },
      fail: () => {
        reject(new Error('生物识别不可用'))
      }
    })
    // #endif

    // #ifdef MP-ALIPAY
    // 支付宝小程序生物识别
    my.ap.faceVerify({
      bizType: 'face',
      bizId: Date.now().toString(),
      success: () => {
        resolve(true)
      },
      fail: (err) => {
        reject(new Error(err.errorMessage || '生物识别失败'))
      }
    })
    // #endif

    // #ifndef MP-WEIXIN
    // #ifndef MP-ALIPAY
    reject(new Error('当前平台不支持生物识别'))
    // #endif
    // #endif
  })
}

/**
 * 获取设备唯一标识
 */
export const getDeviceId = (): string => {
  const platformInfo = getPlatformInfo()

  let systemInfo
  if (typeof window !== 'undefined' && window.uni) {
    systemInfo = uni.getSystemInfoSync()
  } else {
    systemInfo = {
      system: navigator?.platform || 'Unknown',
      platform: 'h5',
      brand: 'H5',
      model: 'Browser',
      pixelRatio: window?.devicePixelRatio || 1,
      screenWidth: window?.screen?.width || 1920,
      screenHeight: window?.screen?.height || 1080
    }
  }

  // 生成设备指纹
  const fingerprint = [
    platformInfo.platform,
    systemInfo.system,
    systemInfo.platform,
    systemInfo.brand,
    systemInfo.model,
    systemInfo.pixelRatio,
    systemInfo.screenWidth,
    systemInfo.screenHeight
  ].join('|')

  // 计算哈希值作为设备ID
  return btoa(fingerprint).replace(/[+/=]/g, '').substring(0, 32)
}

/**
 * 复制到剪贴板
 */
export const copyToClipboard = (text: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof window !== 'undefined' && window.uni) {
      uni.setClipboardData({
        data: text,
        success: () => {
          resolve()
        },
        fail: (err) => {
          reject(new Error((err as any).errMsg || '复制失败'))
        }
      })
    } else if (navigator.clipboard) {
      // 使用现代剪贴板API
      navigator.clipboard.writeText(text).then(resolve).catch(reject)
    } else {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      try {
        document.execCommand('copy')
        document.body.removeChild(textArea)
        resolve()
      } catch (err) {
        document.body.removeChild(textArea)
        reject(new Error('复制失败'))
      }
    }
  })
}

/**
 * 振动反馈
 */
export const vibrate = (type: 'short' | 'long' = 'short') => {
  if (typeof window !== 'undefined' && window.uni) {
    if (type === 'short') {
      uni.vibrateShort?.({})
    } else {
      uni.vibrateLong?.({})
    }
  } else if (navigator.vibrate) {
    // H5环境下的振动支持
    const duration = type === 'short' ? 50 : 200
    navigator.vibrate(duration)
  }
}